<?php

$image_id = $path[3];

if (ctype_digit($image_id)) {
	
	$image = $db->fetchRow("SELECT * FROM cms_images WHERE site_id=? AND id=?", array($site['id'], $image_id));
	list($image['filename_name'], $image['filename_ext']) = preg_extract("/^(.*)\.([^\.]+)/", $image['filename']);
	$image['tags'] = implode("\n", $db->fetchCol("SELECT name FROM cms_images_tags it LEFT JOIN cms_tags t ON it.tag_id=t.id WHERE site_id=? AND it.image_id=?", array($site['id'], $image['id'])));
	
	if ($_POST) {
		if ($_POST['image']['filename_name']) {
			$image = $_POST['image'];
			$image['filename'] = $image['filename_name'] . $image['filename_ext'];
			unset($image['filename_name']);
			unset($image['filename_ext']);
			
			$db->delete('cms_images_tags', $db->quoteInto('image_id=?', $image_id));
			$image['tags'] = explode("\n", $image['tags']);
			foreach($image['tags'] as $tag) {
				
				if (!$tag_id = $db->fetchOne("SELECT id FROM cms_tags WHERE site_id=? AND name=?", array($site['id'], $tag))) {
					$db->insert('cms_tags', array('site_id' => $site['id'], 'name' => $tag));
					$tag_id = $db->lastInsertId();
				}
				$db->insert('cms_images_tags', array('image_id' => $image_id, 'tag_id' => $tag_id));
			}
			unset($image['tags']);
			
			$db->update('cms_images', array_merge($image, array('modified' => new Zend_Db_Expr('NOW()'))), "id={$image_id}");
			$smarty->assign('success', true);
		} else{
			$smarty->assign('errors', array('FILENAME'));
		}
	}
	
	$smarty->assign('image', $image);
	
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
		header('Content-type: text/xml');
		$smarty->display('global/images/_edit_messages.tpl.taconite');
	} else {
		$smarty->display('global/images/edit.tpl.html');
	}
	
} else {
	header("Location: /admin/global/images/");
}